package
{
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.SharedObject;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	//import shine.ui.VariableText;
	/**
	 * 授权使用，用于项目部署验收期的管理
	 * 1、内置一系列序列号，用于授权从安装开始计算的可使用时间（次数）；
	 * 2、授权期到了后，显示对话框在最前面，提示并可输入新的授权；
	 * 3、提示输入序列号的可用性，如已经使用、不存在等；
	 * 4、初始化的时候设定一个值（预设使用次数）；
	 * @author sunge/2013-08-18
	 */
	public class Authorize extends Sprite
	{
		//共30条记录，如果10次为一个序列号，共为300次，按一天启动一次算，可用300天
		//最后一条为永久使用
		private const SNAry:Array = [	"35663963","55327716","47423847",
										"67528544","82638461","53385878",
										"53366563","85556436","22855677",
										"85858211","77226873","75476485",
										"36817323","88597271","72372733",
										"74884242","24672413","59574567",
										"83138434","35241663","24412392",
										"88617372","89837597","39745816",
										"84224788","57667656","47382517",
										"67316179","16575373","58665723",
										"75466184","64646541","84645464",
										"15646532","95646136","75464445",
										"56464114","65489797","24642115",
										"41341331","24242452","63563542"];
		/**
		 * 记住当前序列号，沙箱、程序数据和文件同时存，以时长最长的为准
		 * 沙箱:SO.data.sn
		 * 程序数据:File.applicationStorageDirectory  tmp.txt
		 * 文件:sys/temp/tmp.txt
		 */
		private var SO:SharedObject = SharedObject.getLocal("SungeAuthorize");
		private var DataFilePath:String = File.applicationStorageDirectory.resolvePath("tmp.dat").nativePath;
		private var SysFilePath:String = File.applicationDirectory.resolvePath("sys/temp/tmp.dat").nativePath;
		//提示文字
		private var promptStr:String = "测试暂停，请输入最新的处理编码...";
		//当前次数
		private var currentNum:int;
		private var currentSN:String;
		private var beginSN:String;
		
		private var _stage:Stage;
		private var _dialog:Sprite = new Sprite();
		private var _title:TextField;
		
		
		public function Authorize(beginSN:String = "35663963")
		{
			_title = ViewSet.makeParagraph("",280,14);
			//createSN();
			//***********数据归零***********
			//SO.data.sn = null;
			//SO.flush();
			//var f:File = new File(DataFilePath);
			//f.deleteFile();
			//var f2:File = new File(SysFilePath);
			//f2.deleteFile();
			//*********数据归零结束*********
			
			//trace(beginSN);
			this.beginSN = beginSN;
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		private function begin():void
		{
			//以下的判断不再做，以在开发时灵活测试。(2014-4-22 sunge)
			//初始的SN得在列表中，如果不在，则取第一个
			//if (SNAry.indexOf(beginSN) == -1) {
				//beginSN = SNAry[0];
			//}
			currentSN = beginSN;
			//初始化时比较当前的序列号
			var sn1:String = getSnFromJson(SO.data.sn);
			var sn2:String = getSnFromJson(getFile(DataFilePath));
			var sn3:String = getSnFromJson(getFile(SysFilePath));
			//trace(sn1, sn2, sn3);
			if (!sn1 && !sn2 && !sn3) {
			}else {
				//以最新的SN设置
				currentSN = checkSN(sn1, sn2, sn3);
			}
			currentNum++;
			saveSN();
			//初始化完成.
			//trace(currentNum,currentSN);
			
			//判断
			if (SNAry.indexOf(currentSN) == SNAry.length - 1) {
				//最后一位SN，为永久使用
				return;
			}else {
				var total:int = (SNAry.indexOf(currentSN) + 1) * 10;
				if (currentNum >= total ) {
					//显示对话框
					showDialog();
				}
			}
			
		}
		
		//保存SN
		private function saveSN():void 
		{
			SO.data.sn = createJson(currentSN, currentNum);
			SO.flush();
			writeFile(DataFilePath, createJson(currentSN, currentNum) );
			writeFile(SysFilePath, createJson(currentSN, currentNum) );
		}
		
		private function init(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			_stage = stage;
			//底
			graphics.beginFill(0, 0.6);
			graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
			graphics.endFill();
			
			//对话框
			var dg:Sprite = new Sprite();
			with (dg) {
				graphics.lineStyle(2, 0);
				graphics.beginFill(0xeeeeee);
				graphics.drawRect(0, 0, 300, 100);
				graphics.endFill();
			}
			dg.x = dg.y = 200;
			addChild(dg);
			
			//标题
			_title.x = _title.y = 10;
			//_title.defaultTextFormat = new TextFormat(null, 14);
			_title.text = promptStr;
			dg.addChild(_title);
			
			//输入框
			var txt:TextField = new TextField();
			txt.type = TextFieldType.INPUT;
			txt.border = true;
			txt.background = true;
			txt.defaultTextFormat = new TextFormat(null, 30);
			txt.width = 210;
			txt.height = 40;
			txt.x = 10;
			txt.y = dg.height - 10 - txt.height;
			dg.addChild(txt);
			
			//按钮
			var btn:Sprite = new Sprite();
			with (btn) {
				graphics.beginFill(0x666666);
				graphics.drawRect(0, 0, 60, 40);
				graphics.endFill();
			}
			btn.x = txt.x + txt.width + 10;
			btn.y = txt.y;
			dg.addChild(btn);
			var vt:TextField = ViewSet.makeTxtLine("确 定",14,0xffffff);
			//vt.defaultTextFormat = new TextFormat(null, 14, 0xffffff, true);
			//vt.text = "确 定";
			vt.x = (btn.width - vt.width) / 2;
			vt.y = (btn.height - vt.height) / 2;
			btn.addChild(vt);
			btn.mouseChildren = false;
			btn.buttonMode = true;
			btn.addEventListener(MouseEvent.CLICK, function():void
			{
				if (SNAry.indexOf(txt.text) == -1) {
					_title.text = "输入错误，请确认后重新输入";
				}else {
					if (SNAry.indexOf(txt.text) > SNAry.indexOf(currentSN)) {
						close();
						currentSN = txt.text;
						saveSN();	//保存最新的SN
					}else {
						_title.text = "权限不够，请从开发商处获取。";
					}
				}
			});
			
			close();
			begin();
		}
		
		//显示对话框
		private function showDialog():void 
		{
			_title.text = promptStr;
			_stage.addChild(this);
		}
		private function close():void
		{
			parent.removeChild(this);
		}
		
		private function checkSN(s1:String, s2:String, s3:String):String
		{
			var a:Array = new Array();
			//先排除掉null
			if (s1) a.push(s1);
			if (s2) a.push(s2);
			if (s3) a.push(s3);
			//转换成序号
			for (var i:int; i < a.length; i++) {
				a[i] = SNAry.indexOf(a[i]);
			}
			a.sort(Array.NUMERIC);
			//取序号最大的SN
			return SNAry[a[a.length - 1]];
		}
		
		//从文件获取
		private function getFile(path:String):String
		{
			var f:File = new File(path);
			if (f.exists) {
				var fs:FileStream = new FileStream();
				fs.open(f, FileMode.READ);
				var s:String = fs.readUTFBytes(fs.bytesAvailable);
				fs.close();
				return s;
			}else {
				return null;
			}
		}
		
		//SN写入文件
		private function writeFile(path:String, sn:String):void
		{
			var f:File = new File(path);
			var fs:FileStream = new FileStream();
			fs.open(f, FileMode.WRITE);
			fs.writeUTFBytes(sn);
			fs.close();
		}
		
		private function createJson(sn:String,num:int):String
		{
			var o:Object = { sn:sn, num:num };
			return JSON.stringify(o);
		}
		
		private function getSnFromJson(str:String):String
		{
			//{sn:"",num:1}
			var o:Object = { };
			try {
				o = JSON.parse(str);
				if (currentNum < int(o.num)) {
					currentNum = int(o.num);
				}
			}catch (er:Error) { }
			if (o is Object) {
				return o.sn;
			}else {
				return null;
			}
		}
		
		/**
		 * 生成8位序列号
		 */
		private function createSN():void
		{
			var ary:Array = new Array();
			while (ary.length < 30) {
				var str:String = "";
				while (str.length < 8) {
					var n:int = Math.round(Math.random() * 8) + 1;
					//var s:String = String.fromCharCode(Math.round(Math.random() * 26) + 65);
					str += n;
				}
				//trace(str);
				ary.push(str);
			}
		}
		
	}

}
